<template>
  <div :ref="getPersonButtonRef" @click.stop v-click-outside="onClickOutside">
    <svg-icon :icon-class="isSet ? 'person_icon_active' : 'person_icon'" />
  </div>

  <el-popover
    ref="popoverPersonRef"
    :virtual-ref="buttonPersonRef"
    trigger="click"
    virtual-triggering
    :show-arrow="false"
    :offset="10"
    popper-class="custom-person-popover"
    @show="handelOpenFilter"
    @hide="handelHideFilter"
  >
    <role-list v-if="isOpenPopover" :config-data="responsibleConfigData" @set-person="handelSetPerson" />
  </el-popover>
</template>

<script setup>
import { nextTick, ref, unref, getCurrentInstance } from "vue";
import { ClickOutside as vClickOutside } from "element-plus";
import { cloneDeep } from "lodash";
import RoleList from "./components/RoleList";
import { responsibleConfig } from "@/apis/engineeringManage";

const { proxy } = getCurrentInstance();
const emit = defineEmits(["setPerson"]);

/**
 * 获取当前用户的责任人配置
 */
const isSet = ref(false);
const responsibleConfigData = ref([]);
let catchConfigData = [];
const getResponsibleConfig = async () => {
  const { data } = await responsibleConfig();
  responsibleConfigData.value = (data ?? []).map(item => item.roleId) ?? [];
  catchConfigData = cloneDeep(responsibleConfigData.value);
  isSet.value = !!catchConfigData.length;
};

const buttonPersonRef = ref(null);
const popoverPersonRef = ref(null);
const getPersonButtonRef = e => {
  buttonPersonRef.value = e;
};

const isOpenPopover = ref(false);

// 是否点击外部
const isClickOutside = ref(false);
const onClickOutside = async () => {
  await nextTick();
  isClickOutside.value = true;
  unref(popoverPersonRef).popperRef?.delayHide?.();
};

const handelOpenFilter = async () => {
  await nextTick();
  isOpenPopover.value = true;
  unref(popoverPersonRef).popperRef?.popperInstanceRef?.update();
};
const handelHideFilter = () => {
  if (isClickOutside.value) {
    responsibleConfigData.value = cloneDeep(catchConfigData);
  }
  isOpenPopover.value = false;
};

const handelSetPerson = data => {
  const { data: roleIds, isSet: isSetPerson } = data;
  isSet.value = isSetPerson;
  responsibleConfigData.value = roleIds;
  catchConfigData = cloneDeep(roleIds);
  isClickOutside.value = false;
  popoverPersonRef.value.hide();
  emit("setPerson", data);
};

getResponsibleConfig();
</script>

<style lang="scss">
.custom-person-popover {
  width: fit-content !important;
  padding: 0 !important;
}
</style>
<style scoped lang="scss">
@import "personSet";
</style>
